
import traceback
import logging

from django.shortcuts import render

# Create your views here.
from django.db.models import Q
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework import generics, mixins, views
from django_nameko import get_pool
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi

from account.models import Account, UserFriend, Role
from account.serializers import AccountSerializer
from account.utils import update_inviter_code
from common.utils import LargeResultsSetPagination, get_qiniu_token

logger = logging.getLogger('log')


class Register(APIView):
    """
    注册功能
    """

    def post(self, request):

        data = request.data
        username = data.get('username')
        password = data.get('password')
        phone = data.get('phone')
        inviter_code = data.get('inviter_code')
        if not Account.check_phone(phone):
            return Response({'code': 407, 'message': 'phone is exist'})
        try:
            account = Account.objects.create_user(username=username, password=password)
            account.phone = phone
            account.save()
            # 生成邀请码
            account.create_invited_code()
            update_inviter_code(inviter_code)
            return Response({'code': 200, 'message': 'ok'})
        except:
            error = traceback.format_exc()
            return Response({'code': 500, 'message': error})


class AddFriend(generics.GenericAPIView):
    """
    添加好友
    """
    permission_classes = [permissions.IsAuthenticated]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['friend_id'], properties=
                                  {'friend_id': openapi.Schema(type=openapi.TYPE_STRING, description='好友id')}
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        data = request.data
        user = request.user
        user_id = user.id
        try:
            friend_id = data.get('friend_id')
            friend = Account.objects.filter(id=friend_id).first()
            if not friend:
                return Response({'code': 407, 'message': 'Not find friend'})
            obj, created = UserFriend.objects.get_or_create(user_id=user_id, friend_id=friend_id)
            if not created:
                return Response({'code': 200, 'message': '已经是好友,无法重复添加'})
            obj.save()
            return Response({'code': 200, 'message': '添加成功'})
        except:
            error = traceback.format_exc()
            return Response({'code': 500, 'message': error})


class RemoveFriend(generics.GenericAPIView):
    """
    删除好友
    """
    permission_classes = [permissions.IsAuthenticated]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['friend_id'], properties=
                                  {'friend_id': openapi.Schema(type=openapi.TYPE_STRING, description='好友id')}
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        data = request.data
        user = request.user
        user_id = user.id
        try:
            friend_id = data.get('friend_id')

            obj = UserFriend.objects.filter(user_id=user_id, friend_id=friend_id).first()
            if obj:
                obj.delete()
                return Response({'code': 200, 'message': 'Remove friend ok'})
            else:
                return Response({'code': 408, 'message': '已经删除该好友，无法重复删除'})
        except:
            error = traceback.format_exc()
            return Response({'code': 500, 'message': error})


class SearchFriend(generics.GenericAPIView):
    """
    查找好友
    """
    serializer_class = AccountSerializer
    permission_classes = [permissions.IsAuthenticated]

    query_param = [openapi.Parameter(name='q', in_=openapi.IN_QUERY, description="查询条件", type=openapi.TYPE_STRING),
                   openapi.Parameter(name='size', in_=openapi.IN_QUERY, description="页数大小", type=openapi.TYPE_NUMBER),
                   openapi.Parameter(name='page', in_=openapi.IN_QUERY, description="页码", type=openapi.TYPE_NUMBER),
                   ]

    @swagger_auto_schema(method='get', manual_parameters=query_param)
    @action(methods=['get'], detail=False)
    def get(self, request):
        data = request.query_params
        q = data.get('q')
        if not q:
            result_list = Account.objects.order_by('-id').all()
        else:
            result_list = Account.objects.filter(Q(username__icontains=q) | Q(id__icontains=q)).order_by('-id')

        total_count = result_list.count()

        # 实例化分页对象
        page_cursor = LargeResultsSetPagination()
        # 分页
        data_list = page_cursor.paginate_queryset(result_list, request, view=self)

        data_list = self.get_serializer(data_list, many=True).data
        result = {'code': 200, 'data': data_list, 'total_count': total_count}
        return Response(result)


class GetAccountInfo(generics.GenericAPIView):
    """
    获取用户的详细信息
    """
    serializer_class = AccountSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        user = request.user
        data = self.get_serializer(user).data
        return Response({'code': 200, 'data': data})


class GetQiniuToken(APIView):
    """
    获取七牛 token
    """
    def get(self, request):
        token = get_qiniu_token()
        return Response({'code': 200, 'data': token})
